/**
 * 数据同步API服务
 * 提供同步任务的CRUD操作、执行管理等功能
 */

import api from './api';
import { message } from 'antd';
import { notifySuccess, notifyError } from '../utils/notification';
import type {
  SyncTask,
  SyncTaskCreate,
  SyncTaskUpdate,
  SyncTaskListResponse,
  SyncTaskQueryParams,
  SyncExecution,
  SyncExecutionListResponse,
  SyncExecutionQueryParams,
  SyncExecutionRequest,
  SyncLog,
  SyncLogListResponse,
  SyncLogQueryParams,
  BatchSyncTaskRequest,
  BatchSyncTaskResponse
} from '../types/sync';
import type { BaseResponse } from '../types/common';

class SyncApi {
  private baseUrl = '/v1/sync';

  /**
   * 获取同步任务列表
   */
  async getSyncTasks(params: SyncTaskQueryParams = {}): Promise<SyncTaskListResponse> {
    try {
      const response = await api.get<BaseResponse<SyncTaskListResponse>>(
        this.baseUrl,
        { params }
      );
      return response.data.data;
    } catch (error) {
      message.error('获取同步任务列表失败');
      throw error;
    }
  }

  /**
   * 获取单个同步任务详情
   */
  async getSyncTask(taskId: number): Promise<SyncTask> {
    try {
      const response = await api.get<BaseResponse<SyncTask>>(
        `${this.baseUrl}/${taskId}`
      );
      return response.data.data;
    } catch (error) {
      message.error('获取同步任务详情失败');
      throw error;
    }
  }

  /**
   * 创建同步任务
   */
  async createSyncTask(taskData: SyncTaskCreate): Promise<SyncTask> {
    try {
      const response = await api.post<BaseResponse<SyncTask>>(
        this.baseUrl,
        taskData
      );
      notifySuccess('同步任务创建成功');
      return response.data.data;
    } catch (error) {
      notifyError('创建同步任务失败');
      throw error;
    }
  }

  /**
   * 更新同步任务
   */
  async updateSyncTask(taskId: number, taskData: SyncTaskUpdate): Promise<SyncTask> {
    try {
      const response = await api.put<BaseResponse<SyncTask>>(
        `${this.baseUrl}/${taskId}`,
        taskData
      );
      notifySuccess('同步任务更新成功');
      return response.data.data;
    } catch (error) {
      notifyError('更新同步任务失败');
      throw error;
    }
  }

  /**
   * 删除同步任务
   */
  async deleteSyncTask(taskId: number): Promise<boolean> {
    try {
      const response = await api.delete<BaseResponse<boolean>>(
        `${this.baseUrl}/${taskId}`
      );
      notifySuccess('同步任务删除成功');
      return response.data.data;
    } catch (error) {
      notifyError('删除同步任务失败');
      throw error;
    }
  }

  /**
   * 执行同步任务
   */
  async executeSyncTask(taskId: number, executionRequest: Omit<SyncExecutionRequest, 'task_id'>): Promise<SyncExecution> {
    try {
      const response = await api.post<BaseResponse<SyncExecution>>(
        `${this.baseUrl}/${taskId}/execute`,
        { ...executionRequest, task_id: taskId }
      );
      notifySuccess('同步任务已开始执行');
      return response.data.data;
    } catch (error) {
      notifyError('执行同步任务失败');
      throw error;
    }
  }

  /**
   * 获取同步执行记录列表
   */
  async getSyncExecutions(params: SyncExecutionQueryParams = {}): Promise<SyncExecutionListResponse> {
    try {
      const response = await api.get<BaseResponse<SyncExecutionListResponse>>(
        `${this.baseUrl}/executions/list`,
        { params }
      );
      return response.data.data;
    } catch (error) {
      notifyError('获取执行记录列表失败');
      throw error;
    }
  }

  /**
   * 获取同步执行日志
   */
  async getSyncLogs(executionId: number, params: Omit<SyncLogQueryParams, 'execution_id'> = {}): Promise<SyncLogListResponse> {
    try {
      const response = await api.get<BaseResponse<SyncLogListResponse>>(
        `${this.baseUrl}/executions/${executionId}/logs`,
        { params }
      );
      return response.data.data;
    } catch (error) {
      notifyError('获取同步日志失败');
      throw error;
    }
  }

  /**
   * 下载执行记录的CSV文件
   * @param executionId 执行记录ID
   * @param csvConfig CSV配置参数
   */
  async downloadExecutionCSV(executionId: number, csvConfig?: any): Promise<Response> {
    try {
      // 获取认证令牌 - 从auth_token中获取
      const tokenData = localStorage.getItem('auth_token');
      let token = null;

      if (tokenData) {
        try {
          const parsedToken = JSON.parse(tokenData);
          token = parsedToken.access_token;
        } catch (e) {
          console.error('解析token失败:', e);
        }
      }

      if (!token) {
        throw new Error('未找到有效的认证令牌，请重新登录');
      }

      // 构建URL和查询参数
      let url = `${import.meta.env.VITE_API_BASE_URL}/api/v1/sync/executions/${executionId}/download`;

      // 如果有CSV配置参数，添加到URL查询参数
      if (csvConfig) {
        const params = new URLSearchParams();

        // 添加CSV配置参数
        if (csvConfig.delimiter) params.append('delimiter', csvConfig.delimiter);
        if (csvConfig.quote_char) params.append('quote_char', csvConfig.quote_char);
        if (csvConfig.escape_char) params.append('escape_char', csvConfig.escape_char);
        if (csvConfig.encoding) params.append('encoding', csvConfig.encoding);
        if (csvConfig.escape_special_chars !== undefined) params.append('escape_special_chars', csvConfig.escape_special_chars.toString());

        // 添加查询参数到URL
        url = `${url}?${params.toString()}`;
      }

      // 使用fetch API直接返回Response对象，这样可以处理二进制数据
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        throw new Error(`下载失败: ${response.status} ${response.statusText}`);
      }

      return response;
    } catch (error) {
      notifyError('下载CSV文件失败');
      throw error;
    }
  }



  /**
   * 批量操作同步任务
   */
  async batchSyncTasks(request: BatchSyncTaskRequest): Promise<BatchSyncTaskResponse> {
    try {
      const response = await api.post<BaseResponse<BatchSyncTaskResponse>>(
        `${this.baseUrl}/batch`,
        request
      );

      const actionLabels = {
        enable: '启用',
        disable: '禁用',
        delete: '删除',
        execute: '执行'
      };

      notifySuccess(`批量${actionLabels[request.action]}操作完成`);
      return response.data.data;
    } catch (error) {
      notifyError('批量操作失败');
      throw error;
    }
  }

  /**
   * 启用同步任务
   */
  async enableSyncTask(taskId: number): Promise<SyncTask> {
    return this.updateSyncTask(taskId, { is_active: true });
  }

  /**
   * 禁用同步任务
   */
  async disableSyncTask(taskId: number): Promise<SyncTask> {
    return this.updateSyncTask(taskId, { is_active: false });
  }

  /**
   * 批量启用同步任务
   */
  async batchEnableSyncTasks(taskIds: number[]): Promise<BatchSyncTaskResponse> {
    return this.batchSyncTasks({
      task_ids: taskIds,
      action: 'enable'
    });
  }

  /**
   * 批量禁用同步任务
   */
  async batchDisableSyncTasks(taskIds: number[]): Promise<BatchSyncTaskResponse> {
    return this.batchSyncTasks({
      task_ids: taskIds,
      action: 'disable'
    });
  }

  /**
   * 批量删除同步任务
   */
  async batchDeleteSyncTasks(taskIds: number[]): Promise<BatchSyncTaskResponse> {
    return this.batchSyncTasks({
      task_ids: taskIds,
      action: 'delete'
    });
  }

  /**
   * 批量执行同步任务
   */
  async batchExecuteSyncTasks(taskIds: number[]): Promise<BatchSyncTaskResponse> {
    return this.batchSyncTasks({
      task_ids: taskIds,
      action: 'execute'
    });
  }

  /**
   * 暂停同步执行
   */
  async pauseSyncExecution(executionId: number): Promise<boolean> {
    try {
      const response = await api.post<BaseResponse<boolean>>(
        `${this.baseUrl}/executions/${executionId}/pause`
      );
      notifySuccess('同步任务已暂停');
      return response.data.data;
    } catch (error) {
      notifyError('暂停同步任务失败');
      throw error;
    }
  }

  /**
   * 取消同步执行
   */
  async cancelSyncExecution(executionId: number): Promise<boolean> {
    try {
      const response = await api.post<BaseResponse<boolean>>(
        `${this.baseUrl}/executions/${executionId}/cancel`
      );
      notifySuccess('同步任务已取消');
      return response.data.data;
    } catch (error) {
      notifyError('取消同步任务失败');
      throw error;
    }
  }

  /**
   * 获取任务执行进度（轮询）
   */
  async pollExecutionProgress(
    executionId: number,
    onProgress: (execution: SyncExecution) => void,
    interval: number = 2000
  ): Promise<void> {
    const poll = async () => {
      try {
        const executions = await this.getSyncExecutions({ page: 1, page_size: 1 });
        const execution = executions.items.find(e => e.id === executionId);

        if (execution) {
          onProgress(execution);

          // 如果任务还在运行，继续轮询
          if (execution.status === 'running') {
            setTimeout(poll, interval);
          }
        }
      } catch (error) {
        console.error('轮询执行进度失败:', error);
      }
    };

    poll();
  }

  /**
   * 验证Cron表达式
   */
  validateCronExpression(expression: string): boolean {
    // 简单的Cron表达式验证
    const cronRegex = /^(\*|([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])|\*\/([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])) (\*|([0-9]|1[0-9]|2[0-3])|\*\/([0-9]|1[0-9]|2[0-3])) (\*|([1-9]|1[0-9]|2[0-9]|3[0-1])|\*\/([1-9]|1[0-9]|2[0-9]|3[0-1])) (\*|([1-9]|1[0-2])|\*\/([1-9]|1[0-2])) (\*|([0-6])|\*\/([0-6]))$/;
    return cronRegex.test(expression);
  }

  /**
   * 格式化执行时间
   */
  formatExecutionTime(timeMs?: number): string {
    if (!timeMs) return '-';
    
    const seconds = Math.floor(timeMs / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟${seconds % 60}秒`;
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds % 60}秒`;
    } else {
      return `${seconds}秒`;
    }
  }

  /**
   * 格式化数据量
   */
  formatDataSize(records: number): string {
    if (records >= 1000000) {
      return `${(records / 1000000).toFixed(1)}M`;
    } else if (records >= 1000) {
      return `${(records / 1000).toFixed(1)}K`;
    } else {
      return records.toString();
    }
  }

  /**
   * 下载CSV文件
   */
  async downloadCsvFile(taskId: number): Promise<void> {
    try {
      const response = await api.get(
        `${this.baseUrl}/${taskId}/download`,
        {
          responseType: 'blob',
          headers: {
            'Accept': 'text/csv'
          }
        }
      );

      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let filename = `task_${taskId}_export.csv`;

      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename=(.+)/);
        if (filenameMatch) {
          filename = filenameMatch[1].replace(/"/g, '');
        }
      }

      // 创建下载链接
      const blob = new Blob([response.data], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      notifySuccess('CSV文件下载成功');
    } catch (error: any) {
      if (error.response?.status === 404) {
        notifyError('CSV文件不存在，请先执行同步任务');
      } else if (error.response?.status === 400) {
        notifyError('该任务不是CSV导出任务');
      } else {
        notifyError('下载CSV文件失败');
      }
      throw error;
    }
  }
}

// 创建并导出API实例
export const syncApi = new SyncApi();
export default syncApi;
